<?php
declare(strict_types=1);


namespace App\Fastapp\Mapper;

use App\Fastapp\Model\Account;
use App\Fastapp\Model\AccountInviteLevel;
use App\Fastapp\Model\AccountRecharge;
use App\Fastapp\Model\AccountWithdrawal;
use App\Fastapp\Model\FastappChannelAgent;
use App\System\Mapper\SystemUserMapper;
use Carbon\Carbon;
use Hyperf\Database\Model\Builder;
use Hyperf\Di\Annotation\Inject;
use Mine\Abstracts\AbstractMapper;
use Mine\Exception\NormalStatusException;

/**
 * 代理Mapper类
 */
class FastappChannelAgentMapper extends AbstractMapper
{
    /**
     * @var FastappChannelAgent
     */
    public $model;
    #[Inject]
    public SystemUserMapper $systemUserMapper;

    public function assignModel()
    {
        $this->model = FastappChannelAgent::class;
    }

    /**
     * 搜索处理器
     * @param Builder $query
     * @param array $params
     * @return Builder
     */
    public function handleSearch(Builder $query, array $params): Builder
    {
        // 用户id
        if (isset($params['user_id']) && filled($params['user_id'])) {
            $query->where('user_id', '=', $params['user_id']);
        }

        return $query->with(['admin:id,username,phone,email']);
    }

    public function handlePageItems(array $items, array $params): array
    {
        foreach ($items as $item) {
            $item->setHidden(['admin']);
            $item->username = $item->admin->username;
            $item->phone = $item->admin->phone;
            $item->email = $item->admin->email;
        }
        return $items;
    }

    public function save(array $data): mixed
    {
        $md = Account::query()->where(['gene_id' => $data['user_id']])->first();
        if (!$md) throw new NormalStatusException('用户不存在');
        $admin = [
            'password' => $data['password'],
            'role_ids' => [4],
            'username' => $md->username,
            'email' => $data['email'] ?? $md->email,
            'dept_ids' => [3],
            'nickname' => $md->username,
            'phone' => $data['phone'] ?? $md->mobile,
            'dashboard' => 'agent'
        ];
        $data['admin_id'] = $this->systemUserMapper->save($admin);
        return parent::save($data);
    }

    public function update(mixed $id, array $data): bool
    {
        if (parent::update($id, $data)) {
            $admin_id = $this->model::query()->where(['id' => $id])->value('admin_id');
            $this->systemUserMapper->update($admin_id, $data);
            return true;
        }
        return false;
    }

    public function delete(array $ids): bool
    {
        $admin_ids = $this->model::query()->whereIn('id', $ids)->pluck('admin_id')->toArray();
        $this->systemUserMapper->realDelete($admin_ids);
        return parent::delete($ids);
    }

    public function statistics(): array
    {
        $t = Carbon::now();
        $btw = [$t->toDateString(), $t->addDay()->toDateString()];
        $uid = $this->model::query()->where(['admin_id' => user()->getId()])->value('user_id') ?: 0;
        $uids = AccountInviteLevel::query()->where('link', 'like', $uid . '|%')->pluck('user_id');
        return [
            'account_total' => AccountInviteLevel::query()->where('link', 'like', $uid . '|%')->count(),
            'account_today' => AccountInviteLevel::query()->where('link', 'like', $uid . '|%')->whereBetween('created_at', $btw)->count(),
            'withdrawal_total' => nfmt(AccountWithdrawal::query()->whereIn('user_id', $uids)->whereIn('status', [0, 1])->sum('amount')),
            'withdrawal_today' => nfmt(AccountWithdrawal::query()->whereIn('user_id', $uids)->whereIn('status', [0, 1])->whereBetween('created_at', $btw)->sum('amount')),
        ];
    }

    public function children(int $user_id): array
    {
        $level1 = AccountInviteLevel::query()->where(['parent_id' => $user_id])->pluck('user_id');
        $level2 = AccountInviteLevel::query()->whereIn('parent_id', $level1)->pluck('user_id');
        $level3 = AccountInviteLevel::query()->whereIn('parent_id', $level2)->pluck('user_id');
        $list = [
            [
                'title' => '下一层',
                'total' => $level1->count(),
                'recharge_num' => AccountRecharge::query()->where(['status' => 1])->whereIn('user_id', $level1)->count(),
                'recharge_amount' => AccountRecharge::query()->where(['status' => 1])->whereIn('user_id', $level1)->sum('amount'),
                'withdrawal_num' => AccountWithdrawal::query()->where(['status' => 1])->whereIn('user_id', $level1)->count(),
                'withdrawal_amount' => AccountWithdrawal::query()->where(['status' => 1])->whereIn('user_id', $level1)->sum('amount'),
            ],
            [
                'title' => '下二层',
                'total' => $level2->count(),
                'recharge_num' => AccountRecharge::query()->where(['status' => 1])->whereIn('user_id', $level2)->count(),
                'recharge_amount' => AccountRecharge::query()->where(['status' => 1])->whereIn('user_id', $level2)->sum('amount'),
                'withdrawal_num' => AccountWithdrawal::query()->where(['status' => 1])->whereIn('user_id', $level2)->count(),
                'withdrawal_amount' => AccountWithdrawal::query()->where(['status' => 1])->whereIn('user_id', $level2)->sum('amount'),
            ],
            [
                'title' => '下三层',
                'total' => $level3->count(),
                'recharge_num' => AccountRecharge::query()->where(['status' => 1])->whereIn('user_id', $level3)->count(),
                'recharge_amount' => AccountRecharge::query()->where(['status' => 1])->whereIn('user_id', $level3)->sum('amount'),
                'withdrawal_num' => AccountWithdrawal::query()->where(['status' => 1])->whereIn('user_id', $level3)->count(),
                'withdrawal_amount' => AccountWithdrawal::query()->where(['status' => 1])->whereIn('user_id', $level3)->sum('amount'),
            ],
        ];
        $list[] = [
            'title' => '统计',
            'total' => array_sum(array_column($list, 'total')),
            'recharge_num' => array_sum(array_column($list, 'recharge_num')),
            'recharge_amount' => array_sum(array_column($list, 'recharge_amount')),
            'withdrawal_num' => array_sum(array_column($list, 'withdrawal_num')),
            'withdrawal_amount' => array_sum(array_column($list, 'withdrawal_amount')),
        ];
        return [
            'items' => $list,
            'pageInfo' => [
                'currentPage' => 1,
                'total' => 1,
                'totalPage' => 1,
            ]
        ];
    }
}